package com.luolc.instantmessager.splash;
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016-2017 Luolc
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

import android.content.Intent;
import android.os.Bundle;

import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.EaseUI;
import com.luolc.instantmessager.R;
import com.luolc.instantmessager.base.BaseActivity;
import com.luolc.instantmessager.contact.ContactRepo;
import com.luolc.instantmessager.home.HomeActivity;
import com.luolc.instantmessager.login.LoginActivity;
import com.luolc.instantmessager.util.UiUtils;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class SplashActivity extends BaseActivity {
  private static final int SPLASH_DELAY = 1500;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash_act);
  }

  @Override
  protected void onStart() {
    super.onStart();
    Observable<Boolean> isLoggedIn = Observable
        .just(EMClient.getInstance().isLoggedInBefore())
        .observeOn(Schedulers.io())
        .map(signal -> {
          if (signal) {
            initSdk();
          }
          return signal;
        })
        .map(signal -> {
          if (signal) {
            ContactRepo.getInstance().syncUsers();
            ContactRepo.getInstance().syncGroups();
          }
          return signal;
        })
        .timeout(SPLASH_DELAY, TimeUnit.MILLISECONDS)
        .onErrorReturn(throwable -> EMClient.getInstance().isLoggedInBefore())
        .map(signal -> {
          if (signal) {
            EaseUI.getInstance().setUserProfileProvider(
                ContactRepo.getInstance().createUserProfileProvider());
          }
          return signal;
        });
    Observable<String> completed = Observable.just("start")
        .delay(SPLASH_DELAY, TimeUnit.MILLISECONDS);

    Observable.zip(isLoggedIn, completed, (signal, nothing) -> signal)
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
            signal -> {
              if (signal) {
                startActivity(new Intent(this, HomeActivity.class));
              } else {
                startActivity(new Intent(this, LoginActivity.class));
              }
              finish();
            },
            throwable -> {
              throwable.printStackTrace();
              UiUtils.toast(this, "未知错误：" + throwable.getMessage());
            });
  }

  private void initSdk() {
    EMClient.getInstance().chatManager().loadAllConversations();
    EMClient.getInstance().groupManager().loadAllGroups();
  }
}
